package cn.finder0519.myapplication0621;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.NotNull;
import pub.devrel.easypermissions.EasyPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private static final int REQUEST_CODE = 1024;
    EditText editText;
    SharedPreferences sharedPreferences;
    ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        editText = findViewById(R.id.editText);
        editText.setText(sharedPreferences.getString("content", ""));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem saveToSp = menu.findItem(R.id.save_to_sp);
        saveToSp.setOnMenuItemClickListener(menuItem -> {
            doSaveToSp();
            return true;
        });
        MenuItem saveToFile = menu.findItem(R.id.save_to_file);
        saveToFile.setOnMenuItemClickListener(menuItem -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    doSaveToFile();
                } else {
                    Toast.makeText(MainActivity.this, "Permission should be granted on Android 11+", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + getPackageName()));
                    launcher.launch(intent);
                }
            } else {
                EasyPermissions.requestPermissions(this, "Permission should be granted.", REQUEST_CODE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            return true;
        });
        return true;
    }

    // Save to SharedPreferences
    private void doSaveToSp() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("content", editText.getText().toString());
        editor.apply();
        Toast.makeText(MainActivity.this, "Saved to SharedPreferences", Toast.LENGTH_LONG).show();
    }

    // Save to file in Downloads directory
    private void doSaveToFile() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("content", editText.getText().toString());
        editor.apply();
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
        String formattedDate = format.format(date);
        String fileName = formattedDate + ".txt";
        // Save file on Android 10+
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
            values.put(MediaStore.Downloads.MIME_TYPE, "text/plain");
            Uri uri = getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
            try {
                OutputStream outputStream = getContentResolver().openOutputStream(uri);
                if (outputStream != null) {
                    outputStream.write(editText.getText().toString().getBytes());
                    outputStream.close();
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("File saved");
                    builder.setMessage(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
                    builder.setPositiveButton("OK", null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        // Save file under Android 10
        else {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
            try {
                FileOutputStream stream = new FileOutputStream(file);
                stream.write(editText.getText().toString().getBytes());
                stream.close();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("File saved");
                builder.setMessage(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
                builder.setPositiveButton("OK", null);
                AlertDialog dialog = builder.create();
                dialog.show();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    // Permission grant procession under Android 11
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull @NotNull List<String> perms) {
        if (requestCode == REQUEST_CODE && perms.contains(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) && perms.contains(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
            doSaveToFile();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == REQUEST_CODE && perms.contains(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) && perms.contains(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Toast.makeText(MainActivity.this, "Permission not granted", Toast.LENGTH_LONG).show();
        }
    }
}